package com.sc.admin.common.util;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import com.sc.admin.common.constant.RedisConstant;
import com.sc.admin.common.constant.SystemConstants;
import com.sc.admin.model.dto.UserAuthInfo;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

public class UserInfoUtils {

    /**
     * 获取当前登录人信息
     *
     * @return SysUserDetails
     */
    public static UserAuthInfo getUser() {
        Object loginId;
        try {
            loginId = StpUtil.getLoginId();
        } catch (Exception e) {
            loginId = -1;
        }
        Object obj = RedisUtils.getObj(RedisConstant.USER_INFO + loginId);
        if (obj instanceof UserAuthInfo userInfo) {
            return userInfo;
        }
        return new UserAuthInfo();
    }


    /**
     * 获取用户ID
     *
     * @return Long
     */
    public static Long getUserId() {
        Long userId;
        try {
            userId = Convert.toLong(getUser().getUserId());
        } catch (Exception e) {
            return null;
        }
        return userId;
    }

    /**
     * 获取用户 name
     *
     * @return Long
     */
    public static String getUserName() {
        return Optional.ofNullable(getUser()).orElseGet(UserAuthInfo::new).getUsername();
    }

    public static String getUserName(Object id) {
        return Optional.ofNullable(getUser(id)).orElseGet(UserAuthInfo::new).getUsername();
    }

    /**
     * 获取当前登录人信息
     *
     * @return SysUserDetails
     */
    public static UserAuthInfo getUser(Object id) {
        Object obj = RedisUtils.getObj(RedisConstant.USER_INFO + id.toString());
        if (obj instanceof UserAuthInfo userInfo) {
            return userInfo;
        }
        return new UserAuthInfo();
    }

    public static String getLoginName() {
        return getUserName();
    }

    /**
     * 获取部门ID
     *
     */
    public static Long getDeptId() {
        UserAuthInfo user = getUser();
        if (ObjUtils.isEmpty(user)) {
            return null;
        }
        return Convert.toLong(user.getDeptId());
    }

    /**
     * 获取数据权限范围
     *
     * @return DataScope
     */
    public static Integer getDataScope() {
        return Convert.toInt(getUser().getDataScope());
    }


    /**
     * 获取用户角色集合
     *
     * @return 角色集合
     */
    public static Set<String> getRoles() {
        return new HashSet<>(StpUtil.getRoleList());
    }


    /**
     * 是否超级管理员
     * <p>
     * 超级管理员忽视任何权限判断
     *
     * @return
     */
    public static boolean isRoot() {
        Set<String> roles = getRoles();
        return roles.contains(SystemConstants.ROOT_ROLE_CODE);
    }

}
